# -*- coding: utf-8 -*-


import numpy as np
from sklearn.multiclass import OneVsRestClassifier
from sklearn.metrics import accuracy_score
from sklearn.svm import SVC
import preprocess.bag as bag
import preprocess.CleanUp as CleanUp

class SVM:
    KERNEL_LINEAR='linear'
    KERNEL_SIGMOID='sigmoid'
    KERNEL_POLY='poly'
    KERNEL_RBF='rbf'

    classif=None
    def __init__(self,kernel=KERNEL_LINEAR):
        self.classif = OneVsRestClassifier(SVC(kernel=kernel))
        pass

    def train(self,X,Y,dict=[]):
        X, Y = CleanUp.remove_item_if_feature_empty(X, Y)
        X = bag.FeatureList2OneHot(X,dict)

        X_train = np.array(X)
        Y_train = np.array(Y)
        self.classif.fit(X_train, Y_train)
        pass


    def validation(self,X,Y,dict=[]):
        X, Y = CleanUp.remove_item_if_feature_empty(X, Y)
        X = bag.FeatureList2OneHot(X,dict)

        X_train = np.array(X)
        Y_train = np.array(Y)
        predicted = self.classif.predict(X_train)
        return accuracy_score(predicted, Y_train)

    def cross_validation(self,X,Y,nfold=5,dict=[]):
        X, Y = CleanUp.remove_item_if_feature_empty(X, Y)
        X = bag.FeatureList2OneHot(X,dict)

        from sklearn.model_selection import cross_val_score
        from sklearn.model_selection import ShuffleSplit
        from sklearn import preprocessing
        from sklearn.pipeline import make_pipeline
        X_train = np.array(X)
        Y_train = np.array(Y)
        cv = ShuffleSplit(n_splits=nfold, test_size=.3, random_state=0)

        clf = make_pipeline(preprocessing.StandardScaler(), self.classif)

        scores = cross_val_score(clf, X_train, Y_train, cv=cv)
        return scores.mean()

    def load(self):
        pass


    def save(self):
        pass

if __name__ == '__main__':

    dict = ['a','c']

    features = [
        ['a','b'],
        ['b','c'],
        ['a']
    ]

    labels = [
        [1],
        [2],
        [1]
    ]

    classif = SVM()

    classif.train(features,labels,dict)

    print (classif.validation(features,labels,dict))

    print (classif.cross_validation(features,labels,5,dict))

    pass